var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var route = require('./routes/route');
var func_model = require('./db_curd/sqlite.server.model.js');
var orm = require('orm');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
//修改app.js让ejs模板文件使用扩展名为html的文件
//app.set('view engine', 'ejs');
app.engine('html',require('ejs').renderFile);
app.set('view engine','html');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(path.join(__dirname, 'public')));


// app.use 是应用层中间件
app.use(orm.express("sqlite://./db_curd/db.sqlite3", {
    define: function (db, models) {
        models.Person = func_model.person(db,models);
        models.User = func_model.user(db,models);
        models.WenZhang = func_model.WenZhang(db,models);
        models.bigfenlei = func_model.bigfenlei(db,models);
        models.biaoqian = func_model.biaoqian(db,models);
        models.smallfenlei = func_model.smallfenlei(db,models);
    }
}));
// 将所有路由全部挂载到node下面，为部署时候的反向代理预留接口
app.use('/node', route);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
